package com.xiyou.week05.binarySearch;

/**
 * 69. x的平方根
 *
 * @ClassName：MySqrt
 * @Author：西柚
 * @Date：2022/1/27 2:01 下午
 * @Versiion：1.0
 */
public class MySqrt {

    public int mySqrt(int x) {
        // 找最大的ans，其中满足ans*ans<=x
        int left = 0, right = x;
        while (left < right) {
            int mid = (left + right + 1) / 2;
            if (mid <= x / mid) {
                left = mid;
            } else {
                right = mid - 1;
            }
        }
        return right;
    }

    /**
     * 实数开方
     *
     * @param x
     * @return
     */
    double myRealSqrt(double x) {
        double left = 0, right = x;
        // 如果除不尽，保留7位小数
        while (right - left > 1e-7) {
            double mid = (left + right) / 2;
            if (mid * mid <= x) {
                left = mid;
            } else {
                right = mid;
            }
        }
        return right;
    }

    public static void main(String[] args) {
        MySqrt mySqrt = new MySqrt();
        System.out.println(mySqrt.mySqrt(5));
    }
}
